#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;


//命令行提示符
const int baseSize=1024;
char CommandLine[baseSize];
//指令
int argc=0;
char * argv[baseSize];
char CommandBuffer[baseSize];
//环境变量
char *env[baseSize];
extern char** environ;


string GetPWD()
{
    int i;
    const char *s="PWD";
    for(i=0; env[i]; i++)
    {
        int d=0;
        while(env[i][d] && s[d] && env[i][d]==s[d] )
        {
            d++;
        }
        if(d==3)
            break;
    }


    return env[i]+4;
}

string GetHostName()
{
    return getenv("HOSTNAME");
}

string GetUserName()
{
    return getenv("USER");
}

void PrintCommand()
{

    snprintf(CommandLine,baseSize,"[%s@%s %s]# ",GetUserName().c_str(),GetHostName().c_str(),GetPWD().c_str());

    printf("%s",CommandLine);
    fflush(stdout);
}


bool GetCommand()
{
    char* p= fgets(CommandBuffer,baseSize,stdin);
    CommandBuffer[strlen(CommandBuffer)-1]='\0';
    
    if(p==NULL || strlen(CommandBuffer)==0)
        return false;
    return true;
}

void AnalysisCommand()
{
    memset(argv,0,sizeof(argv));
    argc=0;
    const  char * split=" ";
    argv[argc++]=strtok(CommandBuffer,split);

    while(argv[argc++]=strtok(NULL,split));
    argv[argc--]=NULL;
}


void MakeCommand()
{
    
    if(strcmp(argv[0],"cd")==0)
    {
        chdir(argv[1]);

        int i=0;
        const char *s="PWD";
        for(i=0; env[i]; i++)
        {
            int d=0;
            while(env[i][d] && s[d] && env[i][d]==s[d] )
            {
                d++;
            }
            if(d==3)
                break;
        }
        
        char buffer[1024];
      
        getcwd(buffer,1024);
        printf("%s\n",buffer);
        env[i]=(char *)realloc(env[i],strlen(buffer)+5);
       
        sprintf(env[i],"PWD=%s",buffer);

        return ;
    }

    pid_t id=fork();
    if(id==0)
    {
        //子进程
        execvp(argv[0],argv);
        exit(1);
    }
    waitpid(id,0,0);
}


void InitEnv()
{
    memset(env,0,sizeof(env));
    for(int i=0; environ[i]; i++)
    {
        env[i]=(char *)malloc(strlen(environ[i])+1);
        strcpy(env[i],environ[i]);
    }
}
int main()
{

    InitEnv();

    while(true)
    {
        //1.打印命令行提示符
        PrintCommand();
        //2.获取指令
        if(!GetCommand())
        {
           continue;
        }
        //3.分析指令
        AnalysisCommand(); 
        //4.执行指令
        MakeCommand();
    }
    

    return 0;
}
